<template>
  <div class="project-step">
    <div class="step-header">
      <h3>项目经验</h3>
      <p>请填写您的项目经历</p>
    </div>

    <div class="project-list">
      <div
        v-for="(project, index) in projectList"
        :key="project.id || index"
        class="project-item"
      >
        <el-form
          :model="project"
          :rules="rules"
          label-width="120px"
          class="project-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目名称" prop="name">
                <el-input v-model="project.name" placeholder="请输入项目名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属公司或组织" prop="company_or_organization">
                <el-input v-model="project.company_or_organization" placeholder="请输入所属公司或组织" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="start_date">
                <el-date-picker
                  v-model="project.start_date"
                  type="month"
                  placeholder="请选择开始时间"
                  style="width: 100%"
                  format="YYYY-MM"
                  value-format="YYYY-MM"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="end_date">
                <el-date-picker
                  v-model="project.end_date"
                  type="month"
                  placeholder="请选择结束时间"
                  style="width: 100%"
                  format="YYYY-MM"
                  value-format="YYYY-MM"
                  :disabled="project.is_current"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <el-checkbox v-model="project.is_current">目前进行中</el-checkbox>
          </el-form-item>

          <el-form-item label="个人角色" prop="role">
            <el-input v-model="project.role" placeholder="请输入您在项目中的角色" />
          </el-form-item>

          <el-form-item label="项目概况" prop="overview">
            <el-input
              v-model="project.overview"
              type="textarea"
              placeholder="请简要描述项目的背景、目标和规模"
              :rows="3"
            />
          </el-form-item>

          <el-form-item label="承担任务" prop="responsibilities">
            <el-input
              v-model="project.responsibilities"
              type="textarea"
              placeholder="请详细描述您在项目中承担的具体任务和职责"
              :rows="4"
            />
          </el-form-item>

          <el-form-item label="问题和总结" prop="problems_and_summary">
            <el-input
              v-model="project.problems_and_summary"
              type="textarea"
              placeholder="请描述项目中遇到的问题、解决方案以及个人总结（选填）"
              :rows="3"
            />
          </el-form-item>

          <el-form-item label="使用技术" prop="technologies">
            <el-input
              v-model="project.technologies"
              placeholder="请输入项目中使用的技术栈（选填）"
            />
          </el-form-item>

          <el-form-item label="项目成果" prop="achievements">
            <el-input
              v-model="project.achievements"
              type="textarea"
              placeholder="请描述项目取得的成果和效果（选填）"
              :rows="2"
            />
          </el-form-item>

          <el-form-item label="项目链接" prop="url">
            <el-input
              v-model="project.url"
              placeholder="请输入项目演示链接或代码仓库地址（选填）"
            />
          </el-form-item>

          <div class="form-actions">
            <el-button @click="removeProject(index)" v-if="projectList.length > 1">
              删除
            </el-button>
          </div>
        </el-form>
      </div>
    </div>

    <div class="step-actions">
      <el-button @click="addProject">
        <el-icon><Plus /></el-icon>
        添加项目经验
      </el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        保存项目经验
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, type FormRules } from 'element-plus'
import { projectApi, type Project } from '@/api/resume'

// Props
interface Props {
  resumeId: number
}

// Emits
interface Emits {
  (e: 'completed', completed: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const projectList = ref<Project[]>([])

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  start_date: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  role: [
    { required: true, message: '请输入个人角色', trigger: 'blur' }
  ],
  overview: [
    { required: true, message: '请输入项目概况', trigger: 'blur' }
  ],
  responsibilities: [
    { required: true, message: '请输入承担任务', trigger: 'blur' }
  ]
}

// 监听项目变化，判断是否完成
watch(projectList, () => {
  checkCompletion()
}, { deep: true })

// 检查完成状态
const checkCompletion = () => {
  const hasValidProject = projectList.value.some(project =>
    project.name && project.start_date && project.role &&
    project.overview && project.responsibilities
  )
  emit('completed', hasValidProject)
}

// 获取项目列表
const fetchProjectList = async () => {
  loading.value = true
  try {
    const response = await projectApi.getProjectList(props.resumeId)
    const data = response.data || response

    if (data.results && data.results.length > 0) {
      projectList.value = data.results
    } else if (Array.isArray(data) && data.length > 0) {
      projectList.value = data
    } else {
      addProject()
    }
  } catch (error) {
    addProject()
  } finally {
    loading.value = false
  }
}

// 添加项目
const addProject = () => {
  projectList.value.push({
    name: '',
    start_date: '',
    end_date: '',
    is_current: false,
    company_or_organization: '',
    overview: '',
    role: '',
    responsibilities: '',
    problems_and_summary: '',
    technologies: '',
    achievements: '',
    url: '',
    order: projectList.value.length
  })
}

// 删除项目
const removeProject = async (index: number) => {
  const project = projectList.value[index]

  if (project.id) {
    try {
      await projectApi.deleteProject(props.resumeId, project.id)
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败')
      return
    }
  }

  projectList.value.splice(index, 1)
}

// 保存项目经验
const handleSave = async () => {
  saving.value = true
  try {
    for (const project of projectList.value) {
      // 跳过空的项目
      if (!project.name || !project.overview || !project.responsibilities) {
        continue
      }

      if (project.id) {
        // 更新
        await projectApi.updateProject(props.resumeId, project.id, project)
      } else {
        // 创建
        const response = await projectApi.createProject(props.resumeId, project)
        const data = response.data || response
        project.id = data.id
      }
    }

    ElMessage.success('项目经验保存成功')

    // 重新获取数据
    await fetchProjectList()

  } catch (error) {
    console.error('保存项目经验错误:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 生命周期
onMounted(() => {
  fetchProjectList()
})
</script>

<style lang="scss" scoped>
.project-step {
  .step-header {
    margin-bottom: 32px;

    h3 {
      font-size: 24px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin: 0 0 8px 0;
    }

    p {
      color: var(--text-color-secondary);
      margin: 0;
    }
  }

  .project-list {
    .project-item {
      border: 1px solid var(--border-color-light);
      border-radius: 8px;
      padding: 24px;
      margin-bottom: 20px;
      background: var(--bg-color);

      &:last-child {
        margin-bottom: 0;
      }

      .project-form {
        .form-actions {
          text-align: right;
          margin-top: 16px;
          padding-top: 16px;
          border-top: 1px solid var(--border-color-extra-light);
        }
      }
    }
  }

  .step-actions {
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid var(--border-color-extra-light);
    display: flex;
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .project-step {
    .project-list {
      .project-item {
        padding: 16px;

        .project-form {
          .el-row {
            .el-col {
              margin-bottom: 16px;
            }
          }
        }
      }
    }
  }
}
</style>
